//
//  HNCommentMouldVM.m
//  优学荟管理系统
//
//  Created by 星道 on 2017/10/6.
//  Copyright © 2017年 星道三好. All rights reserved.
//

#import "HNCommentMouldVM.h"

@implementation HNCommentMouldVM
{
    UITableView *_TableView;
    NSInteger _Index;
    NSInteger _TempIndex;
    NSMutableArray *_DataArr;
}

/** 配置tableView */
- (void)ConfigTableView:(UITableView *)TableView {

    _TableView = TableView;
    _DataArr = [NSMutableArray array];
    _TableView.tableFooterView = [UIView new];
    _TableView.tableHeaderView = [UIView new];
    [_TableView registerNib:[UINib nibWithNibName:[HNCommentMouldCell description] bundle:nil] forCellReuseIdentifier:@"Cell"];
    _TableView.rowHeight = 134*KScale;
    _TableView.delegate = self;
    _TableView.dataSource = self;
    _TableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{

        _TempIndex = _Index;
        _Index = 1;
        [self RefreshData];
    }];
    _TableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{

        [self RefreshData];
    }];
    [_TableView.mj_header beginRefreshing];
}

/** 请求失败处理下标 */
- (void)MgrPage {
    if (_Index == 1) {
        _Index = _TempIndex;
    }
}

/** 添加模板，回传模板标题 */
- (void)AddComplete:(void (^)(NSString *))Complete name:(NSString *)name{

    UIAlertController *Alert = [UIAlertController alertControllerWithTitle:name message:nil preferredStyle:(UIAlertControllerStyleAlert)];
    [Alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"请输入模板名称";
    }];
    UIAlertAction *CanelAction = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil];
    [CanelAction setValue:ColorRGB(102, 102, 102) forKey:@"_titleTextColor"];
    [Alert addAction:CanelAction];
    UIAlertAction *SureAction = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        UITextField *TextField = Alert.textFields.firstObject;
        if (TextField.text.length > 0) {
            Complete ? Complete(TextField.text):nil;
        } else {
            [SVProgressHUD showErrorWithStatus:@"无模板名称,添加失败"];
        }
    }];
    [SureAction setValue:ColorRGB(49, 204, 131) forKey:@"_titleTextColor"];
    [Alert addAction:SureAction];
    [self.VC presentViewController:Alert animated:YES completion:nil];
}

/** 发出请求 */
- (void)RefreshData {

    NSDictionary *Params = @{
                             @"action":@"listTemplateByOid",
                             @"pageNumber":@(_Index)
                             };
    [NetManager Get:LLBaseURL(@"yxhUser.do") Auth:YES Params:Params Success:^(id Obj) {
        [_TableView.mj_footer endRefreshing];
        [_TableView.mj_header endRefreshing];
        if ([Obj[@"code"] isEqualToNumber:@1000]) {
            if ([Obj[@"t"][@"dataList"] count] <= 0) {
                [_TableView.mj_footer endRefreshingWithNoMoreData];
            } else {
                if (_Index == 1) {
                    [_DataArr removeAllObjects];
                }
                [Obj[@"t"][@"dataList"] enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    [_DataArr addObject:[HNCommentMouldModel HNObjectValuesForKey:obj]];
                }];
                _Index += 1;
                [_TableView reloadData];
            }
        } else {
            [self MgrPage];
            [HUD showError:Obj[@"msg"]];
        }
    } Fail:^(NSError *Error) {
        [self MgrPage];
        [HUD showError:NetErr];
        [_TableView.mj_footer endRefreshing];
        [_TableView.mj_header endRefreshing];
    }];
}


#pragma mark - tableView delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return _DataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    HNCommentMouldCell *Cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    if (_DataArr.count > indexPath.row) {
        Cell.Model = _DataArr[indexPath.row];
        Cell.Delegate = (id)self.VC;
    }
 
    return Cell; 
}


/** 删除模板 */
- (void)Delete:(NSNumber *)ID Complete:(void (^)())Complete {
    UIAlertController *Alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"是否确认删除该模板?" preferredStyle:(UIAlertControllerStyleActionSheet)];
    [Alert addAction:[UIAlertAction actionWithTitle:@"删除" style:(UIAlertActionStyleDestructive) handler:^(UIAlertAction * _Nonnull action) {
        [SVProgressHUD showWithStatus:@"请稍候"];
        NSDictionary *Params = @{
                                 @"action":@"delTemplateById",
                                 @"id"    :ID
                                 };
        [NetManager Get:LLBaseURL(@"yxhUser.do") Auth:YES Params:Params Success:^(id Obj) {
            if ([Obj[@"code"] isEqualToNumber:@1000]) {
                [SVProgressHUD showSuccessWithStatus:@"删除模板成功"];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    Complete ? Complete():nil;
                });
            } else {
                [SVProgressHUD showErrorWithStatus:Obj[@"msg"]];
            }
        } Fail:^(NSError *Error) {
            [SVProgressHUD showErrorWithStatus:NetErr];
        }];
    }]];
    [Alert addAction:[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil]];
    [self.VC presentViewController:Alert animated:YES completion:nil];
}

/** 刷新 表单 */
- (void)ReloadTableView:(NSNumber *)ID {

    __block HNCommentMouldModel *Model = nil;
    [_DataArr enumerateObjectsUsingBlock:^(HNCommentMouldModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([ID isEqualToNumber:obj.ID]) {
            Model = obj;
            *stop = YES;
        }
    }];
    [_DataArr removeObject:Model];
    [_TableView reloadSections:[[NSIndexSet alloc] initWithIndex:0] withRowAnimation:(UITableViewRowAnimationAutomatic)];
}

- (void)RefreshTableView {
    
    [_TableView.mj_header beginRefreshing];
}
@end
